//
//  DoubleSlider.m
//  Sweeter
//
//  Created by Dimitris on 23/06/2010.
//  Copyright 2010 locus-delicti.com. All rights reserved.
//

#import "DoubleSlider.h"

#define kMinHandleDistance          10.0
#define kBoundaryValueThreshold     0.01
#define kMovingAnimationDuration    0.3
//#ff8d31
//颜色
#define kUIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
//create the gradient
static const CGFloat colors [] = { 
    222/255, 218/255, 218/255, 1.0,
	222/255, 218/255, 218/255, 1.0
};

//define private methods
@interface DoubleSlider (PrivateMethods)
- (void)updateValues;
- (void)addToContext:(CGContextRef)context roundRect:(CGRect)rrect withRoundedCorner1:(BOOL)c1 corner2:(BOOL)c2 corner3:(BOOL)c3 corner4:(BOOL)c4 radius:(CGFloat)radius;
- (void)updateHandleImages;
@end


@implementation DoubleSlider

@synthesize minSelectedValue, maxSelectedValue;
@synthesize minHandle, maxHandle;

-(UIColor *) hexStringToColor: (NSString *) stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    
    if ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}
- (void) dealloc
{
	CGColorRelease(bgColor);
	self.minHandle = nil;
	self.maxHandle = nil;
//	[super dealloc];
}

#pragma mark Object initialization

- (id) initWithFrame:(CGRect)aFrame minValue:(float)aMinValue maxValue:(float)aMaxValue barHeight:(float)height
{
    self = [super initWithFrame:aFrame];
    if (self)
	{
		if (aMinValue < aMaxValue) {
			minValue = aMinValue;
			maxValue = aMaxValue;
		}
		else {
			minValue = aMaxValue;
			maxValue = aMinValue;
		}
        valueSpan = maxValue - minValue;
		sliderBarHeight = height;
        sliderBarWidth = self.frame.size.width / self.transform.a;  //calculate the actual bar width by dividing with the cos of the view's angle
		
		self.minHandle = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn_screen_price.png"] highlightedImage:[UIImage imageNamed:@"btn_screen_price.png"]];
		self.minHandle.center = CGPointMake(sliderBarWidth * 0.2, aFrame.size.height * 0.5);
		[self addSubview:self.minHandle];
        //最小值
        self.minlbl = [[UILabel alloc] initWithFrame:CGRectMake(self.minHandle.frame.origin.x, self.minHandle.frame.origin.y, 100.0, 30.0)];
        self.minlbl.backgroundColor = [UIColor clearColor];
        self.minlbl.userInteractionEnabled = YES;
        CGAffineTransform rotation = CGAffineTransformMakeRotation(-M_PI_2);
        self.minlbl.transform = rotation;
        self.minlbl.center = CGPointMake(self.minHandle.center.x, self.minHandle.center.y-80);
        self.minlbl.text = [NSString stringWithFormat:@"￥%.0f",self.minSelectedValue];
        self.minlbl.font = [UIFont fontWithName:@"Arial" size:12.0];
        [self addSubview:self.minlbl];
        
		self.maxHandle = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn_screen_price.png"] highlightedImage:[UIImage imageNamed:@"btn_screen_price.png"]];
		self.maxHandle.center = CGPointMake(sliderBarWidth * 0.8, aFrame.size.height * 0.5);
		[self addSubview:self.maxHandle];
//最大值
        self.maxlbl = [[UILabel alloc] initWithFrame:CGRectMake(self.maxHandle.frame.origin.x, self.maxHandle.frame.origin.y, 100.0, 30.0)];
        self.maxlbl.backgroundColor = [UIColor clearColor];
        self.maxlbl.userInteractionEnabled = YES;
        self.maxlbl.transform = rotation;
        self.maxlbl.center = CGPointMake(self.maxHandle.center.x, self.maxHandle.center.y-80);
        self.maxlbl.text = [NSString stringWithFormat:@"￥%.0f",self.maxSelectedValue];
        self.maxlbl.font = [UIFont fontWithName:@"Arial" size:12.0];
        [self addSubview:self.maxlbl];

//		bgColor = CGColorRetain([UIColor colorWithRed:226/255.0 green:141/255 blue:35/255 alpha:1.0].CGColor);
        bgColor = CGColorRetain(kUIColorFromRGB(0xff8d31).CGColor);
		self.backgroundColor = [UIColor clearColor];
		
		//init
        latchMin = NO;
        latchMax = NO;
		[self updateValues];
	}
	return self;
}

- (void) moveSlidersToPosition:(NSNumber *)leftSlider: (NSNumber *)rightSlider animated:(BOOL)animated {
    CGFloat duration = animated ? kMovingAnimationDuration : 0.0;
    [UIView transitionWithView:self duration:duration options:UIViewAnimationOptionCurveLinear
                    animations:^(void){
                        self.minHandle.center = CGPointMake(sliderBarWidth * ((float)[leftSlider intValue] / 100), sliderBarHeight * 0.5);
                        self.maxHandle.center = CGPointMake(sliderBarWidth * ((float)[rightSlider intValue] / 100), sliderBarHeight * 0.5);
                        self.minlbl.center = CGPointMake(self.minHandle.center.x, self.minHandle.center.y-80);
                        self.maxlbl.center = CGPointMake(self.maxHandle.center.x, self.maxHandle.center.y-80);
                        [self updateValues];
                        //force redraw
                        [self setNeedsDisplay];
                        //notify listeners
                        [self sendActionsForControlEvents:UIControlEventValueChanged];
                    }
                    completion:^(BOOL finished) {
                    }];
}


+ (id) doubleSlider
{
	return [[self alloc] initWithFrame:CGRectMake(-20., 75., 150., 100.) minValue:0.0 maxValue:100.0 barHeight:0.5];
}
//-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
//     CGPoint touchPoint = [[touches anyObject] locationInView:self];
//    NSLog(@"%@",[NSValue valueWithCGPoint:touchPoint]);
//}
//-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
//{
//     CGPoint touchPoint = [[touches anyObject] locationInView:self];
//        NSLog(@"%@",[NSValue valueWithCGPoint:touchPoint]);
//}
//-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
//{
//    
//}
#pragma mark Touch tracking

-(BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint touchPoint = [touch locationInView:self];
//    CGRect  maxrect = CGRectMake(self.maxHandle.frame.origin.x, self.maxHandle.frame.origin.y, self.maxHandle.frame.size.width+30.0, self.maxHandle.frame.size.height+30.0);
    CGRect  minframe = CGRectMake(self.minHandle.frame.origin.x, self.minHandle.frame.origin.y, self.minHandle.frame.size.width, self.minHandle.frame.size.height+50);
    
    CGRect  maxframe = CGRectMake(self.maxHandle.frame.origin.x, self.maxHandle.frame.origin.y, self.maxHandle.frame.size.width, self.maxHandle.frame.size.height+50);
    if ( CGRectContainsPoint(minframe, touchPoint) || CGRectContainsPoint(self.minlbl.frame, touchPoint) ) {
		latchMin = YES;
	}
	else if ( CGRectContainsPoint(maxframe, touchPoint) ) {
		latchMax = YES;
	}
    [self updateHandleImages];
    return YES;
}

- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
	CGPoint touchPoint = [touch locationInView:self];
    CGRect  minframe = CGRectMake(self.minHandle.frame.origin.x, self.minHandle.frame.origin.y, self.minHandle.frame.size.width, self.minHandle.frame.size.height+50);
    
    CGRect  maxframe = CGRectMake(self.maxHandle.frame.origin.x, self.maxHandle.frame.origin.y, self.maxHandle.frame.size.width, self.maxHandle.frame.size.height+50);
	if ( latchMin || CGRectContainsPoint(minframe, touchPoint) ) {
		if (touchPoint.x < self.maxHandle.center.x - kMinHandleDistance && touchPoint.x > 0.0) {
			self.minHandle.center = CGPointMake(touchPoint.x, self.minHandle.center.y);
            self.minlbl.center = CGPointMake(self.minHandle.center.x, self.minHandle.center.y-80);
            self.minlbl.text = [NSString stringWithFormat:@"￥%.0f",self.minSelectedValue];
			[self updateValues];
		}
	}
	else if ( latchMax || CGRectContainsPoint(maxframe, touchPoint) ) {
		if (touchPoint.x > self.minHandle.center.x + kMinHandleDistance && touchPoint.x < sliderBarWidth) {
			self.maxHandle.center = CGPointMake(touchPoint.x, self.maxHandle.center.y);
            self.maxlbl.center = CGPointMake(self.maxHandle.center.x, self.maxHandle.center.y-80);
            self.maxlbl.text = [NSString stringWithFormat:@"￥%.0f",self.maxSelectedValue];
			[self updateValues];
		}
	}
	// Send value changed alert
	[self sendActionsForControlEvents:UIControlEventValueChanged];
    
	//redraw
	[self setNeedsDisplay];
	return YES;
}

-(void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    latchMin = NO;
    latchMax = NO;
    [self updateHandleImages];
}

#pragma mark Custom Drawing

- (void) drawRect:(CGRect)rect
{
	//FIX: optimise and save some reusable stuff
    UIColor * colorh = [self hexStringToColor:@"#ff8d31"];
//    CGColorRef hColor = colorh.CGColor;
    
    CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
    CGColorSpaceRelease(baseSpace), baseSpace = NULL;
	
    CGContextRef context = UIGraphicsGetCurrentContext();
	CGContextClearRect(context, rect);
	
	CGRect rect1 = CGRectMake(0.0, self.frame.size.width*0.5, self.minHandle.center.x, sliderBarHeight);
	CGRect rect2 = CGRectMake(self.minHandle.center.x, self.frame.size.width*0.5, self.maxHandle.center.x - self.minHandle.center.x, sliderBarHeight);
	CGRect rect3 = CGRectMake(self.maxHandle.center.x, self.frame.size.width*0.5, sliderBarWidth - self.maxHandle.center.x, sliderBarHeight);
    	
    CGContextSaveGState(context);
	
    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect)-10);
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect)-10);
	
	//add the right rect
	[self addToContext:context roundRect:rect3 withRoundedCorner1:NO corner2:YES corner3:YES corner4:NO radius:0.0f];
	//add the left rect
	[self addToContext:context roundRect:rect1 withRoundedCorner1:YES corner2:NO corner3:NO corner4:YES radius:0.0f];
	
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    
	CGGradientRelease(gradient), gradient = NULL;
    CGContextSetFillColorWithColor(context,CGColorRetain(kUIColorFromRGB(0xdedada).CGColor));
    CGContextFillRect(context, rect); //画一个方框
	//draw middle rect
    CGContextRestoreGState(context);
	CGContextSetFillColorWithColor(context, bgColor);
	CGContextFillRect(context, rect2);
		
	[super drawRect:rect];
}

- (void)addToContext:(CGContextRef)context roundRect:(CGRect)rrect withRoundedCorner1:(BOOL)c1 corner2:(BOOL)c2 corner3:(BOOL)c3 corner4:(BOOL)c4 radius:(CGFloat)radius
{	
	CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect);
	CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), maxy = CGRectGetMaxY(rrect);
	
	CGContextMoveToPoint(context, minx, midy);
	CGContextAddArcToPoint(context, minx, miny, midx, miny, c1 ? radius : 0.0f);
	CGContextAddArcToPoint(context, maxx, miny, maxx, midy, c2 ? radius : 0.0f);
	CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, c3 ? radius : 0.0f);
	CGContextAddArcToPoint(context, minx, maxy, minx, midy, c4 ? radius : 0.0f);
}


#pragma mark Helper

- (void)updateHandleImages
{
    self.minHandle.highlighted = latchMin;
    self.maxHandle.highlighted = latchMax;
}

- (void)updateValues
{
	self.minSelectedValue = minValue + self.minHandle.center.x / sliderBarWidth * valueSpan;
    //snap to min value
    if (self.minSelectedValue < minValue + kBoundaryValueThreshold * valueSpan) self.minSelectedValue = minValue;
        
    self.maxSelectedValue = minValue + self.maxHandle.center.x / sliderBarWidth * valueSpan;
    //snap to max value
    if (self.maxSelectedValue > maxValue - kBoundaryValueThreshold * valueSpan) self.maxSelectedValue = maxValue;
    
    
    self.maxlbl.text = [NSString stringWithFormat:@"￥%.0f",self.maxSelectedValue];

    self.minlbl.text = [NSString stringWithFormat:@"￥%.0f",self.minSelectedValue];
}

@end